package scc.Dao;

import java.sql.*;
import javax.swing.JOptionPane;

public class GenericDAO {

    public Connection getConnection(){
        try {
            System.out.println("Conectando...");
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost/controlm", "sa", "Admin1234");
            //Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://172.16.0.216/test", "test", "Admin1234");
            System.out.println("Conectado a CONTROLM!");
            return con;            
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
            return null;
        }
    }

    public Statement getStatement() throws SQLException{
        return getConnection().createStatement();
    }

    public PreparedStatement getStatement(String st) throws SQLException{
        return getConnection().prepareStatement(st);
    }

    public ResultSet executeQuery(String query, Object... params) throws SQLException{
        PreparedStatement ps = getStatement(query);
        for (int i = 0; i < params.length; i++){
            ps.setObject(i+1, params[i]);
        }
        return ps.executeQuery();
    }

    public int executeCommand(String query, Object... params) throws SQLException{
        PreparedStatement ps = getStatement(query);
        System.out.println(query);
        for (int i = 0; i < params.length; i++){
            ps.setObject(i+1, params[i]);
        }
        int result = ps.executeUpdate();
        return result;
    }

}
